/**
 * @author harry
 * @date 2022/3/2/17:49
 */

package com.serviceOrchestration.factory;

import com.serviceOrchestration.pojo.Product;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@Component
public class ProductFactory {

    private static final ThreadLocal<SimpleDateFormat> dateFormat = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyyMMddhhmmss"));

    /**
     * 注入product的属性值，也只注入属性值
     * @param properties 属性值
     * @return 创建的产品。如果参数中出现不存在的属性名则返回null
     */
    public Product make(Map<String, Object> properties, boolean available) {
        // 生成id
        properties.put("id", generateId());

        Product product = new Product();
        product.setAvailable(available);
        for(String key : properties.keySet()) {
            try {
                Field field = Product.class.getDeclaredField(key);
                field.setAccessible(true);
                field.set(product, properties.get(key));
            } catch (NoSuchFieldException | IllegalAccessException e) {
                e.printStackTrace();
                return null;
            }
        }
        return product;
    }

    private String generateId() {
        return dateFormat.get().format(new Date());
    }
}
